//
//  MCMusicPlaybaseListVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/31.
//

import UIKit
import JXSegmentedView
import SnapKit
import ObjectMapper
import Toast_Swift
import MJRefresh
import Kingfisher
import ZFPlayer

typealias musicPlayInfoBlock = (_ musicPlay:MCMusicRecord) ->Void

class MCMusicPlaybaseListVc: MCBaseVc {
    
    public var musictIndexType = 0
    
    var musicTableView:UITableView!
    
    private var dataSource:Array = [MCMusicRecord?]()
    
    
    private let MCMusicPlayBaseTableIdentifier = "MCMusicPlayBaseTableIdentifier"
    
    private var current:Int = 1
    
    var musicPlayBlock:musicPlayInfoBlock?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        
        musicTableView = UITableView.init(frame: CGRect.zero, style:.plain)
        musicTableView.dataSource = self
        musicTableView.delegate = self
        musicTableView.separatorStyle = .none
        musicTableView.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        self.view.addSubview(musicTableView)
        musicTableView.snp.makeConstraints { make in
            make.left.equalTo(self.view.snp.left).offset(0.0)
            make.right.equalTo(self.view.snp.right).offset(0.0)
            make.bottom.equalTo(self.view.snp.bottom).offset(0.0)
            make.top.equalTo(self.view.snp.top).offset(0.0)
        }
     
        self.musicTableView.register(UINib.init(nibName: "MCMusicTableCell", bundle: Bundle.main), forCellReuseIdentifier: MCMusicPlayBaseTableIdentifier)
        self.musicTableView.rowHeight = 74
        
        self.musicTableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.current = 1
            self.getMusicPlaylistData(current: self.current)
        })
        
        self.musicTableView.mj_header?.beginRefreshing()
        
        self.musicTableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {
            self.getMusicPlaylistData(current: self.current)
        })
    }
    
    func getMusicPlaylistData(current:Int?) -> Void {
        NetWorkRequest(MCMusicApi.musicApi(current: current, bgmName:"",bgmType: musictIndexType)) { ResponseModel in
            self.musicTableView.mj_header?.endRefreshing()
            self.musicTableView.mj_footer?.endRefreshing()
            let musicListModel = MCMusicListModel(JSONString: ResponseModel.dataString)
            if musicListModel?.records?.isEmpty == false {
                
                if current == 1 {
                    self.dataSource.removeAll()
                    self.dataSource.append(contentsOf: musicListModel?.records ?? [])
                }else {
                    self.dataSource.append(contentsOf: musicListModel?.records ?? [])
                }
                
                self.musicTableView.reloadData()
                
            }
            
        } failureCallback: { ResponseModel in
            self.musicTableView.mj_header?.endRefreshing()
            self.musicTableView.mj_footer?.endRefreshing()
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
}


extension MCMusicPlaybaseListVc:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MCMusicTableCell = tableView.dequeueReusableCell(withIdentifier: MCMusicPlayBaseTableIdentifier, for: indexPath) as! MCMusicTableCell
        let recordsList = self.dataSource[indexPath.row]
        
        cell.titleLabel.text = recordsList?.bgmName
        cell.headerImageView.kf.setImage(with:URL(string: recordsList?.pictureUrl ?? ""))
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let recordsList = self.dataSource[indexPath.row] else {
            return
        }
        self.musicPlayBlock?(recordsList)
        
        // FIXME: 音频不能播放。。。
        if let bgmUrlStr = recordsList.bgmUrl, let url = URL(string: bgmUrlStr) {
            // 创建AVPlayerItem
            let playerItem = AVPlayerItem(url: url)
            // 创建AVPlayer
            let player = AVPlayer(playerItem: playerItem)
            // 播放音频
            player.play()
        }
        
    }
    
}

extension MCMusicPlaybaseListVc:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
